package com.example.myapplication.fragment

import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.bumptech.glide.Glide
import com.drake.brv.utils.linear
import com.drake.brv.utils.models
import com.drake.brv.utils.setup
import com.example.myapplication.MainViewModel
import com.example.myapplication.R
import com.example.myapplication.databinding.ApplyAccountItemLayoutBinding
import com.example.myapplication.databinding.FragmentMyRewardBinding
import com.example.myapplication.databinding.MyRewardItemLayoutBinding
import com.example.myapplication.db.ApplyUser
import com.example.myapplication.db.Reward
import com.example.myapplication.utils.TimeUtils
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class MyRewardFragment : BaseFragment<FragmentMyRewardBinding>() {
    private val mViewModel: MainViewModel by activityViewModels()
    private val gson = Gson() // 将 Gson 声明为类成员，以便在整个类中使用

    override fun initBinding(): FragmentMyRewardBinding {
        return FragmentMyRewardBinding.inflate(layoutInflater)
    }

    override fun initView() {
        val timeUtils = TimeUtils()
        var thisAccount = ""

        // 观察登录用户
        mViewModel.Logged_user.observe(viewLifecycleOwner, Observer {
            thisAccount = it
            Log.d("MyRewardFragment", "Logged in as: $thisAccount")
            val thisUser = mViewModel.findUserByAccount(thisAccount)
            val listType = object : TypeToken<List<Reward>>() {}.type

            if (thisUser != null) {
                val rewards: List<Reward> = try {
                    if (thisUser.reward.isNotEmpty()) {
                        gson.fromJson(thisUser.reward, listType) ?: emptyList()
                    } else {
                        emptyList()
                    }
                } catch (e: Exception) {
                    Log.e("MyRewardFragment", "Error parsing rewards", e)
                    emptyList()
                }
                Log.d("MyRewardFragment", "Parsed rewards: ${rewards.size}")
                mBinding.myRewardRecyclewView.models = rewards
            } else {
                Log.e("MyRewardFragment", "User not found: $thisAccount")
            }
        })

        // 设置 RecyclerView 的布局管理器
        mBinding.myRewardRecyclewView.layoutManager = LinearLayoutManager(context)

        // 设置 RecyclerView 的适配器和绑定逻辑
        mBinding.myRewardRecyclewView.linear().setup {
            addType<Reward>(R.layout.my_reward_item_layout)
            onBind {
                val binding = getBinding<MyRewardItemLayoutBinding>()
                val model = getModel<Reward>()

                // 加载用户图标
                Glide.with(context)
                    .load(R.drawable.user)
                    .into(binding.ivIcon)

                binding.tvTitle.text = model.account
                binding.tvCountry.text = model.content
                binding.time.text = timeUtils.splitDateTime(model.time)
                binding.state.visibility = View.VISIBLE
                binding.isEnd.visibility = if(model.isEnd) View.VISIBLE else View.GONE

                // 定义 ApplyUser 的类型
                val listType = object : TypeToken<List<ApplyUser>>() {}.type

                // 安全解析 rewardApplyAccountList，防止空字符串导致的 NullPointerException
                val applyUsers: List<ApplyUser> = if (model.rewardApplyAccountList.isNotEmpty()) {
                    try {
                        gson.fromJson(model.rewardApplyAccountList, listType) ?: emptyList()
                    } catch (e: Exception) {
                        Log.e("MyRewardFragment", "Error parsing rewardApplyAccountList", e)
                        emptyList()
                    }
                } else {
                    emptyList()
                }

                // 设置申请状态文本
                val thisUserApplyState = when {
                    !model.hasGone -> "正在悬赏"
                    model.hasGone && !model.isEnd -> "正在进行"
                    model.isEnd -> "已经结束"
                    else -> ""
                }
                if(model.hasGone){
                    binding.isEnd.visibility=View.VISIBLE
                }
                binding.state.text = thisUserApplyState
                binding.price.text = "${model.price}￥"

                // 点击事件，导航到 RewardFragment
                itemView.setOnClickListener {
                    mViewModel.findUserByAccount(thisAccount).also {
                        mViewModel.thisRewardContext.value = model
                    }
                    findNavController().navigate(R.id.action_myRewardFragment_to_rewardFragment)
                }

                // 设置嵌套的 ApplyUser RecyclerView
                binding.applyUser.linear().setup {
                    addType<ApplyUser>(R.layout.apply_account_item_layout)
                    onBind {
                        val applyAccountBinding = getBinding<ApplyAccountItemLayoutBinding>()
                        val modelApplyAccount = getModel<ApplyUser>() // 正确获取 ApplyUser 模型

                        applyAccountBinding.name.text = modelApplyAccount.account
                        applyAccountBinding.selfIntroduction.text = mViewModel.findUserByAccount(modelApplyAccount.account)?.selfIntroduction ?: "无简介"
                        binding.isEnd.setOnClickListener {
                            updateApplyUserState(model, modelApplyAccount, newState = 3)
                        }
                        // 处理允许和拒绝按钮的点击事件
                        applyAccountBinding.allow.setOnClickListener {
                            updateApplyUserState(model, modelApplyAccount, newState = 2)
                        }
                        applyAccountBinding.refuse.setOnClickListener {
                            updateApplyUserState(model, modelApplyAccount, newState = 0)
                        }
                    }
                }

                // 赋值 ApplyUser 模型列表
                binding.applyUser.models = applyUsers
            }
        }

        // 返回按钮点击事件
        mBinding.back.setOnClickListener {
            findNavController().popBackStack()
        }
    }

    /**
     * 更新 ApplyUser 的状态，并保存到数据库
     *
     * @param reward 当前的 Reward 对象
     * @param applyUser 需要更新的 ApplyUser 对象
     * @param newState 新的状态值
     */
    private fun updateApplyUserState(reward: Reward, applyUser: ApplyUser, newState: Int) {
        // 定义 ApplyUser 的类型
        val applyUserListType = object : TypeToken<MutableList<ApplyUser>>() {}.type

        // 安全解析 rewardApplyAccountList，防止空字符串导致的 NullPointerException
        val applyUsers: MutableList<ApplyUser> = if (reward.rewardApplyAccountList.isNotEmpty()) {
            try {
                gson.fromJson<MutableList<ApplyUser>>(reward.rewardApplyAccountList, applyUserListType) ?: mutableListOf()
            } catch (e: Exception) {
                Log.e("MyRewardFragment", "Error parsing rewardApplyAccountList during update", e)
                mutableListOf()
            }
        } else {
            mutableListOf()
        }

        // 查找需要更新的 ApplyUser
        val targetApplyUser = applyUsers.find { it.account == applyUser.account }
        if (targetApplyUser != null) {
            // 更新 ApplyUser 的状态
            targetApplyUser.state = newState
        } else {
            Log.e("MyRewardFragment", "ApplyUser not found: ${applyUser.account}")
            return
        }

        // 重新计算 hasGone 和 isEnd
        var thisHasGone = false
        var thisIsEnd = false
        applyUsers.forEach {
            if (it.state == 2 || it.state == 3) {
                thisHasGone = true
            }
            if (it.state == 3) {
                thisIsEnd = true
            }
        }

        // 序列化回 JSON 字符串
        reward.rewardApplyAccountList = gson.toJson(applyUsers)
        reward.hasGone = thisHasGone
        reward.isEnd = thisIsEnd

        // 更新数据库中的用户数据
        lifecycleScope.launch(Dispatchers.IO) {
            // 假设 reward.account 是发布该奖励的用户账号
            val rewardOwner = mViewModel.findUserByAccount(reward.account)
            if (rewardOwner != null) {
                // 找到对应的 Reward 对象并更新 rewardApplyAccountList
                val updatedRewards = try {
                    if (rewardOwner.reward.isNotEmpty()) {
                        gson.fromJson<MutableList<Reward>>(rewardOwner.reward, object : TypeToken<MutableList<Reward>>() {}.type) ?: mutableListOf()
                    } else {
                        mutableListOf()
                    }
                } catch (e: Exception) {
                    Log.e("MyRewardFragment", "Error parsing user rewards during update", e)
                    mutableListOf()
                }

                // 找到对应的 Reward 并更新 rewardApplyAccountList、hasGone 和 isEnd
                val targetReward = updatedRewards.find { it.time == reward.time }
                if (targetReward != null) {
                    targetReward.rewardApplyAccountList = reward.rewardApplyAccountList
                    targetReward.hasGone = reward.hasGone
                    targetReward.isEnd = reward.isEnd
                    // 将更新后的 rewards 列表序列化回 JSON 字符串
                    rewardOwner.reward = gson.toJson(updatedRewards)
                    // 更新用户数据到数据库
                    mViewModel.updateUser(rewardOwner)
                    Log.d("MyRewardFragment", "Updated ApplyUser (${applyUser.account}) state to $newState for Reward (${reward.time})")
                } else {
                    Log.e("MyRewardFragment", "Reward not found for time: ${reward.time}")
                }
            } else {
                Log.e("MyRewardFragment", "Reward owner not found: ${reward.account}")
            }
        }

        // 刷新 UI 以反映状态的变化
        lifecycleScope.launch(Dispatchers.Main) {
            // 重新解析并更新 UI
            val listType = object : TypeToken<List<Reward>>() {}.type
            val thisUser = mViewModel.findUserByAccount(reward.account)
            if (thisUser != null) {
                val rewards: List<Reward> = try {
                    if (thisUser.reward.isNotEmpty()) {
                        gson.fromJson(thisUser.reward, listType) ?: emptyList()
                    } else {
                        emptyList()
                    }
                } catch (e: Exception) {
                    Log.e("MyRewardFragment", "Error parsing rewards during UI update", e)
                    emptyList()
                }
                mBinding.myRewardRecyclewView.models = rewards
            }
        }

        Log.d("MyRewardFragment", "Updated ApplyUser (${applyUser.account}) state to $newState for Reward (${reward.time})")
    }
}
